<script setup lang="ts">
import type {
  IAddressConfig,
  IAddressRule,
  IAddressRuleGroup,
} from './types.ts'

import { v4 as uuidV4 } from 'uuid'
import AddressRuleGroup from './AddressRuleGroup.vue'

type ConfigureFn = (arr: IAddressConfig[]) => IAddressConfig[]
interface IEmit {
  (event: 'update:modelValue', value: IAddressRuleGroup[]): void
}

interface IProps {
  disabledAll?: boolean
  modelValue: IAddressRuleGroup[]
  // 匹配规则配置函数，会传入系统内置的所有规则配置，外部调用者可对系统配置进行覆盖重置
  configure?: ConfigureFn | ConfigureFn[]
}

const props = defineProps<IProps>()
const emit = defineEmits<IEmit>()
const groupRefs = ref<(typeof AddressRuleGroup)[]>([])
const addressModeGroups = useVModel(props, 'modelValue', emit)
provide('groups', addressModeGroups)

/**
 * 组规则改变
 */
function handleGroupRuleChange(uuid: string, rules: IAddressRule[]) {
  const group = addressModeGroups.value.find(item => item.uuid === uuid)
  if (group) {
    group.addresses = rules
  }
}

/**
 * 重置
 */
function reset() {
  addressModeGroups.value = [
    {
      uuid: uuidV4(),
      addresses: [{ uuid: uuidV4(), ip: '', status: 1 }],
    },
  ]
  console.log('addressModeGroups.value: ', addressModeGroups.value)
}

// 验证数据
async function validate() {
  const res = await Promise.all(
    groupRefs.value.map(groupComp => groupComp.validate()),
  )
  return res.map((res: any) => res.every((item: any) => item === undefined))[0]
}

defineExpose({
  reset,
  validate,
})
</script>

<template>
  <div class="address-mode-collection-view">
    <div
      v-for="(group, index) in addressModeGroups"
      :key="group.uuid"
      class="address-mode-view"
    >
      <div class="address-mode-view__top">
        <div class="field w-[192px]">
          地址 IP
        </div>
        <div class="field w-[128px]">
          模式
        </div>
        <div class="field w-[32px]">
          操作
        </div>
      </div>
      <div class="address-mode-view__body">
        <address-rule-group
          ref="groupRefs"
          v-model:rules="group.addresses"
          :last="index === addressModeGroups.length - 1"
          :disabled-all="disabledAll"
          @delete="addressModeGroups.splice(index, 1)"
          @change="handleGroupRuleChange(group.uuid, $event)"
        />
      </div>
    </div>
  </div>
</template>

<style lang="less">
@import './styles.less';
</style>
